package com.bilibili.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bilibili.dao.UserMomentsMapper;
import com.bilibili.domain.entity.UserMoments;
import com.bilibili.domain.exception.ConditionException;
import com.bilibili.service.UserMomentsService;
import com.bilibili.utils.RocketMQUtil;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

import static com.bilibili.domain.constant.UserMomentsConstant.TOPIC_MOMENTS;

/**
* @author www
* @description 针对表【t_user_moments(用户动态表)】的数据库操作Service实现
* @createDate 2024-06-09 14:42:07
*/
@Service
public class UserMomentsServiceImpl extends ServiceImpl<UserMomentsMapper, UserMoments>
    implements UserMomentsService {

    @Resource
    private UserMomentsMapper userMomentsMapper;

    //获取rocketmq的配置
    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    private LambdaQueryWrapper<UserMoments> wrapper = new LambdaQueryWrapper<>();

    @Override
    @Transactional
    public void addUserMoments(UserMoments userMoments) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        userMoments.setCreateTime(new Date());
        userMoments.setUpdateTime(new Date());
        userMomentsMapper.insert(userMoments);

        DefaultMQProducer producer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        Message msg = new Message(TOPIC_MOMENTS, JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8));
        RocketMQUtil.syncSendMsg(producer,msg);
    }

    //TODO:redis中没有数据，暂时未找到bug，先使用查询数据库代替
    @Override
    @Transactional
    public List<UserMoments> geyUserSubscribedMoments(Long userId) {
//        //从redis中取出数据
//        String key = "subscribed-"+userId;
//        String listStr = redisTemplate.opsForValue().get(key);
//        List<UserMoments> list= JSONArray.parseArray(listStr, UserMoments.class);
//        return list;
        wrapper.eq(UserMoments::getUserId,userId);
        List<UserMoments> list = userMomentsMapper.selectList(wrapper);
        return list;
    }
}




